package utils;

import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectToMapUtils {

    /**
     * @ApiModelProperty 注解 - 转换为 Map
     * @param object
     * @return
     */
    public static Map<String, Object> objectToMap(Object object){
        Map<String,Object> dataMap = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                field.setAccessible(true);
//                dataMap.put(field.getName(),field.get(object));
                if (field.getAnnotation(ApiModelProperty.class) != null) {
                    dataMap.put(field.getAnnotation(ApiModelProperty.class).value(), field.get(object));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return dataMap;
    }


    /**
     * data关键字map转换 无data关键字map
     * @param parMap
     * @return
     */
    public static HashMap<String, Object> templateDataKeyHashMapToKey(Map<String, String> parMap){
        HashMap<String, Object> resultMap = new HashMap<>();
        String key = "";
        for (Map.Entry<String,String> entry : parMap.entrySet()){
            key = "";

            if (StringUtils.isNotBlank(entry.getKey()) && entry.getKey().contains("${data.")){
                key = entry.getKey().substring(7, entry.getKey().length()-1);
            }else {
                key = entry.getKey();
            }

            resultMap.put(key, entry.getValue());
        }

        return resultMap;
    }

}
